package com.yuzhitong.shapi.net;

import android.annotation.SuppressLint;

import com.yuzhitong.shapi.base.Contents;

import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit单例类
 * 创建Retrofit
 */
public class RetrofitClient {

    private static volatile RetrofitClient instance;
    private APIService apiService;
    private final String baseUrl = Contents.BASE_URL;
    private Retrofit retrofit;
    private OkHttpClient okHttpClient;

    private RetrofitClient() {
    }

    /**
     * 单例
     *
     * @return Retrofit
     */
    public static RetrofitClient getInstance() {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new RetrofitClient();
                }
            }
        }
        return instance;
    }

    /**
     * 设置Header
     */
    private Interceptor getHeaderInterceptor() {
        return chain -> {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder();
            /*// 添加Token
//                        .header("token", "");*/
            Request request = requestBuilder.build();
            return chain.proceed(request);
        };

    }

    /**
     * 设置拦截器 打印日志
     */
    private Interceptor getInterceptor() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //显示日志
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        return interceptor;
    }

    public OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            //如果为DEBUG 就打印日志
            if (Contents.DEBUG) {
                okHttpClient = new OkHttpClient().newBuilder()
                        //设置Header
                        .addInterceptor(getHeaderInterceptor())
                        .proxySelector(new ProxySelector() {
                            @Override
                            public List<Proxy> select(URI uri) {
                                return Collections.singletonList(Proxy.NO_PROXY);
                            }

                            @Override
                            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {

                            }
                        })
                        //设置拦截器
                        .addInterceptor(getInterceptor())
                        .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), new MyX509TrustManager())
                        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                        .callTimeout(60, TimeUnit.SECONDS)
                        .build();
            } else {
                okHttpClient = new OkHttpClient().newBuilder()
                        //设置Header
                        .addInterceptor(getHeaderInterceptor())
//                                                .addInterceptor(getInterceptor())
                        .proxySelector(new ProxySelector() {
                            @Override
                            public List<Proxy> select(URI uri) {
                                return Collections.singletonList(Proxy.NO_PROXY);
                            }

                            @Override
                            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {

                            }
                        })
                        .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), new MyX509TrustManager())
                        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                        .callTimeout(60, TimeUnit.SECONDS)
                        .build();
            }

        }
        return okHttpClient;
    }

    /**
     * 获取APIService
     */
    public APIService getApi() {
        //初始化一个client,不然retrofit会自己默认添加一个
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    //设置网络请求的Url地址
                    .baseUrl(baseUrl)
                    //设置数据解析器
                    .addConverterFactory(GsonConverterFactory.create())
                    //设置网络请求适配器，使其支持RxJava与RxAndroid
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .client(getOkHttpClient())
                    .build();
        }
        //创建—— 网络请求接口—— 实例
        if (apiService == null) {
            apiService = retrofit.create(APIService.class);
        }

        return apiService;
    }

    /*
    /**
     * 获取下载APIService
     *
     * @param baseUrl 下载使用的BaseUrl
     */
    /*
//    public APIService getDownloadApi(String baseUrl) {
//        //初始化一个client,不然retrofit会自己默认添加一个
//        if (retrofit == null) {
//            retrofit = new Retrofit.Builder()
//                    //设置网络请求的Url地址
//                    .baseUrl(baseUrl)
//                    //设置数据解析器
//                    .addConverterFactory(GsonConverterFactory.create())
//                    //设置网络请求适配器，使其支持RxJava与RxAndroid
//                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
//                    .client(getOkHttpClient())
//                    .build();
//        }
//        //创建—— 网络请求接口—— 实例
//        if (apiService == null) {
//            apiService = retrofit.create(APIService.class);
//        }
//
//        return apiService;
//    }
     */


    @SuppressLint("CustomX509TrustManager")
    private static class MyX509TrustManager implements X509TrustManager {

        @SuppressLint("TrustAllX509TrustManager")
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {

        }

        @SuppressLint("TrustAllX509TrustManager")
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

}
